/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.mindorks.demo.slice;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jcodecraeer.xrecyclerview.ProgressStyle;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.mindorks.demo.InfiniteFeedInfo;
import com.mindorks.demo.MyAdapter;
import com.mindorks.demo.ResourceTable;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Component;
import ohos.agp.utils.Color;
import ohos.app.Context;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;
import ohos.global.resource.ResourceManager;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

/**
 * DemoLoadMoreAbilitySlice
 *
 * @since 2021-05-27
 */
public class DemoLoadMoreAbilitySlice extends AbilitySlice {
    private XRecyclerView mRecyclerView;
    private MyAdapter<InfiniteFeedInfo> mAdapter;
    private ArrayList<InfiniteFeedInfo> listData;
    private List<InfiniteFeedInfo> feedList;

    private final EventHandler handler = new EventHandler(EventRunner.getMainEventRunner());

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_demo_load_more);

        initView();
    }

    private void initView() {
        mRecyclerView = (XRecyclerView) findComponentById(ResourceTable.Id_abt_linear_xrecyclerview);
        mRecyclerView.setLongClickable(false);
        mRecyclerView.setPullRefreshEnabled(false);
        mRecyclerView.setLoadingMoreProgressStyle(ProgressStyle.BallPulse);
        mRecyclerView.setLoadingMoreProgressIndicatorColor(Color.RED.getValue());
        mRecyclerView.getDefaultFootView().setProgressVisibility(Component.VISIBLE);

        mRecyclerView.getDefaultFootView().setLoadingHint("加载中...");
//        mRecyclerView.getDefaultFootView().setNoMoreHint("");
//        mRecyclerView.getDefaultFootView().setNoMoreHint("自定义加载完毕提示");

        final int itemLimit = 4;
//        mRecyclerView.setLimitNumberToCallLoadMore(2);
        handler.postTask(refreshRunnable, 1000);

        mRecyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
            }

            @Override
            public void onLoadMore() {
                System.out.println("onLoadMore ---------- ");
                if (listData.size() <= 20) {
                    new EventHandler(EventRunner.getMainEventRunner()).postTask(new Runnable() {
                        @Override
                        public void run() {
                            for (int i = 0; i < itemLimit; i++) {
                                listData.add(feedList.get(i));
                            }
                            if (mRecyclerView != null) {
                                try {
                                    Thread.sleep(1500);
                                } catch (InterruptedException e) {
                                    e.fillInStackTrace();
                                }
                                mRecyclerView.loadMoreComplete();
                                mAdapter.notifyDataChanged();
                            }
                        }
                    }, 1000);
                } else {
                    mRecyclerView.setNoMore(true);
                }
            }
        });

        listData = new ArrayList<>();
        feedList = loadInfiniteFeeds(getContext());
        mAdapter = new MyAdapter<>(getContext(), feedList, ResourceTable.Layout_list_item);
        mAdapter.setOnItemClickListener(new XRecyclerView.RecyclerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(Component component, int position) {
            }
        });
        mRecyclerView.setItemProvider(mAdapter);
        mRecyclerView.refresh();
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    private final Runnable refreshRunnable = new Runnable() {
        @Override
        public void run() {
            listData.clear();
            for (int i = 0; i < 6; i++) {
                listData.add(feedList.get(i));
            }
            mAdapter.notifyDataChanged();
            if (mRecyclerView != null)
                mRecyclerView.refreshComplete();
        }
    };

    /**
     * 加载资源文件信息
     *
     * @param context 上下文
     * @return 数据集合
     */
    public static List<InfiniteFeedInfo> loadInfiniteFeeds(Context context) {
        List<InfiniteFeedInfo> infiniteFeedInfos = null;
        Gson gson = new Gson();
        infiniteFeedInfos = gson.fromJson(loadJSONFromAsset(context), new TypeToken<List<InfiniteFeedInfo>>() {
        }.getType());
        return infiniteFeedInfos;
    }

    private static String loadJSONFromAsset(Context context) {
        ResourceManager resManager = context.getResourceManager();
        ohos.global.resource.RawFileEntry rawFileEntry = resManager.getRawFileEntry("resources/rawfile/infinite_news.json");
        StringBuffer stringBuffer = new StringBuffer();
        try {
            BufferedReader bf = new BufferedReader(new InputStreamReader(rawFileEntry.openRawFile()));
            String line;
            while ((line = bf.readLine()) != null) {
                stringBuffer.append(line);
            }
        } catch (IOException ex) {
            ex.fillInStackTrace();
            return null;
        }
        return stringBuffer.toString();
    }
}
